package com.itheima.d2_reflect_test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

/*
    对象框架
    目标：保存任意对象的字段和其数据到文件中去
 */
public class ObjectFrame {
    public static void saveObj(Object obj) throws Exception {
        //1. 把数据保存到文件
        BufferedWriter bw = new BufferedWriter(new FileWriter("user.dir", true));
        //2.获取class对象
        Class clazz = obj.getClass();
        bw.write("===================="+clazz.getSimpleName()+"=====================");
        bw.newLine();
        bw.flush();
        //3.获取class对象的所有的成员变量
        Field[] declaredFields = clazz.getDeclaredFields();
        //4.遍历数组 获得每一个变量成员
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            Object value = declaredField.get(obj);
            //写入内容
            bw.write(name+"="+value);
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }
}














